<?php
// +----------------------------------------------------------------------
// | 微梦系统[ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2024 北京微梦世创科技有限公司
// | 官方网站: https://bjwmsc.com
// +----------------------------------------------------------------------
// | Author: @Tinymeng 666@majiameng.com
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace App\Services\Admin;

use App\Models\ConstCode;
use App\Models\MysqlDb\CompanyModel;
use App\Models\MysqlDb\ConfigDataModel;
use App\Models\MysqlDb\ConfigModel;
use App\Models\MysqlDb\ConfigWebsiteModel;
use App\Services\BaseService;

/**
 * 配置管理-服务类
 * @author Tinymeng
 * @date: 2023/3/28 11:25
 */
class WebSiteService extends BaseService
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new ConfigModel();
    }

    /**
     * 获取数据列表
     * @return array
     * @author Tinymeng
     * @date: 2023/3/28 11:26
     */
    public function getList()
    {
        $cid = getCid();
        $where = [
            'mark'=>ConstCode::STATUS_NORMAL
        ];
        if($cid == ConstCode::ADMIN_CID){
            $company_name = '平台';
            $where['open'] = ConstCode::STATUS_DELETE;
        }else{
            $company = CompanyModel::getByid($cid);
            $company_name = $company['name']??'';
            $where['open'] = ConstCode::STATUS_NORMAL;
        }

        // 获取配置列表
        $configList = $this->model
            ->where($where)
            ->orderBy("sort", "asc")
            ->get()
            ->toArray();
        $list = [];
        if ($configList) {
            $config_id_array = [];
            foreach ($configList as $val) {
                $config_id_array[] = $val['id'];
            }

            //获取公司配置值
            $where = [
                'cid'=>$cid,
                'mark'=>ConstCode::STATUS_NORMAL,
            ];
            $configDataModel = new ConfigWebsiteModel();
            $companyConfigData = $configDataModel->where($where)
                ->get()
                ->toArray();
            $companyConfigDataArray = [];
            foreach ($companyConfigData as $value){
                $companyConfigDataArray[$value['code']] = $value['value'];
            }

            //获取系统中配置项
            $where = [
                'mark'=>ConstCode::STATUS_NORMAL,
            ];
            $configDataModel = new ConfigDataModel();
            $systemConfigData = $configDataModel->whereIn("config_id", $config_id_array)
                ->where($where)
                ->orderBy("sort", "ASC")
                ->get()
                ->toArray();
            $systemConfigDataArray = [];
            foreach ($systemConfigData as $value){
                if(!empty($companyConfigDataArray[$value['code']])){
                    $value['value'] = $companyConfigDataArray[$value['code']];//公司配置
                }
                $systemConfigDataArray[$value['config_id']][] = $this->loadData($value);
            }
            foreach ($configList as &$val) {
                $item = array();
                $item['config_id'] = $val['id'];
                $item['config_name'] = $val['name'];
                $item['item_list'] = $systemConfigDataArray[$val['id']]??[];
                $list[] = $item;
            }
        }

        $result = [
            'list'=>$list,
            'company_name'=>$company_name,
        ];
        return message("操作成功", true, $result);
    }

    /**
     * 格式化数据
     * @param $v
     * @return mixed
     */
    public function loadData($v)
    {
            if ($v['type'] == "array" || $v['type'] == "radio" || $v['type'] == "select") {
                $data = preg_split('/[\r\n]+/s', $v['options']);
                if ($data) {
                    $arr = [];
                    foreach ($data as $vt) {
                        $value = preg_split('/[:]+/s', $vt);
                        $arr[$value[0]] = $value[1];
                    }
                    $v['param'] = $arr;
                }
            }
            // 复选框
            if ($v['type'] == "checkbox") {
                // 组件值
                $v['value'] = explode(",", $v['value']);
                // 组件选项
                $data = preg_split('/[\r\n]+/s', $v['options']);
                if ($data) {
                    $arr = [];
                    foreach ($data as $vt) {
                        $value = preg_split('/[:：]+/s', $vt);
                        $arr[] = [
                            'label' => $value[1],
                            'value' => $value[0]
                        ];
                    }
                    $v['param'] = $arr;
                }
            }
            // 单图
            if ($v['type'] == "image" && !empty($v['value'])) {
                $v['value'] = get_image_url($v['value']);
            }
            // 多图
            if ($v['type'] == "images") {
                $urlList = explode(",", $v['value']);
                $itemList = [];
                foreach ($urlList as $vt) {
                    if (empty($vt)) {
                        continue;
                    }
                    $itemList[] = get_image_url($vt);
                }
                $v['value'] = $itemList;
            }
        return $v;
    }

    /**
     * 保存配置
     * @return array
     * @author Tinymeng
     * @date: 2023/3/28 11:27
     */
    public function edit()
    {
        // 参数
        $data = request()->all();
        if (!$data) {
            return message("参数不能为空", false);
        }
        unset($data['cid']);

        $preg = "/^http(s)?:\\/\\/.+/";// 图片链接正则
        foreach ($data as $key => &$val) {
            // 图片处理
            if (is_string($val) && preg_match($preg, $val)) {
                if (str_contains($val, "temp")) {
                    $val = save_image($val, 'config');
                } else if (str_contains($val, IMG_URL)) {
                    $val = str_replace(IMG_URL, "", $val);
                }

            }
            if (is_array($val)) {
                $item = [];
                foreach ($val as $vt) {
                    if (preg_match($preg, $vt)) {
                        if (str_contains($vt, "temp")) {
                            $vt = save_image($vt, 'config');
                        } else {
                            $vt = str_replace(IMG_URL, "", $vt);
                        }
                        $item[] = $vt;
                    } else {
                        $item[] = $vt;
                    }
                }
                $val = !empty($item) ? implode(",", $item) : "";
            }

            $where = [
                ["cid", "=", getCid()],
                ["code", "=", $key],
            ];
            $info = [
                "cid" => getCid()
            ];
            $configWebsiteModel = new ConfigWebsiteModel();
            $configWebsite = $configWebsiteModel->where($where)->first();
            if(empty($configWebsite)){
                $info['code'] = $key;
            }else{
                $info['id'] = $configWebsite['id'];
            }
            $info['value'] = $val;
            $configWebsiteModel->edit($info);
        }
        return message();
    }
}
